package com.itheima.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.entity.UserGift;
import com.itheima.entity.UserGiftLog;
import com.itheima.mapper.UserGiftLogMapper;
import com.itheima.mapper.UserGiftMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.Random;


/**
 * @author liudo
 * @version 1.0
 * @project mybatis-plus-quick-start
 * @date 2023/12/22 15:58:20
 */
@RestController
public class UserGiftController {

    @Autowired
    private UserGiftMapper userGiftMapper;

    @Autowired
    private UserGiftLogMapper userGiftLogMapper;

    private static final LocalDateTime START = LocalDateTime.of(2023, 12, 22, 17, 05);

    @GetMapping("/gift/{username}")
    @Transactional
    public String gift(@PathVariable String username) {
        LocalDateTime now = LocalDateTime.now();
        if (now.isBefore(START)) {
            return "活动尚未开始！";
        }
        // 乐观锁 -- 5, 0
        UserGift userGift = userGiftMapper.selectById(1);
        UserGiftLog userGiftLog = new UserGiftLog();
        userGiftLog.setUsername(username);
        userGiftLog.setCreatedAt(LocalDateTime.now());

        // 分流 -  判断你有没有资格去扣库存
        // 随机数  1~100000000000 2~3  如果这个用户拿到的是1
        // 预约 - 限制中奖人数
        Random random = new Random();
        int nextInt = random.nextInt(4);
        if (nextInt != 1) {
            return "未中奖！";
        }

        if (userGift.getAmount() > 0) {
            userGiftLog.setGiftId(userGift.getId());
            userGiftLog.setStatus(1);

            userGift.setAmount(userGift.getAmount() - 1);
            // 5, 0 ---> 4,1 -- where version = 0   1
            int updated = userGiftMapper.updateById(userGift);
            if (updated == 0) {
                userGiftLog.setStatus(0);
            }
        } else {
            userGiftLog.setStatus(0);
        }
        userGiftLogMapper.insert(userGiftLog);
        return userGiftLog.getStatus() == 0 ? "未中奖" : "中奖啦~";
    }
}
